import { Button, Modal, Form, Input, message } from 'antd';
import { useState } from 'react';
import { postDraft } from '../../api/draft';
import { useAuth } from '../../context/AuthProvider';
// 布局结构
// 封装发布投稿的请求函数
// 交互(确定发布的事件)

const PostDraft = ({draft,setDraft}) => {
    const {user} = useAuth();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const onFinish = (values)=>{
        postDraft({...values,draftUser: user.userId})
            .then(res=>{
                console.log(res)
                setDraft(
                    {
                        ...draft,
                        content: [{...res.data,user},...draft.content],
                    }
                )
                setIsModalOpen(false);
                message.success('发布成功')
            })
            .finally(()=>{
                
            })
    }

    return (
        <>
            <Button
                type="primary"
                onClick={showModal}
            >
                新增投稿
            </Button>
            <Modal
                title="新增投稿"
                open={isModalOpen}
                footer={null}
                onCancel={handleCancel}
            >
                <Form
                    name="basic"
                    layout='vertical'
                    // style={{ width: 400, margin: '50px auto' }}
                    onFinish={onFinish}
                    autoComplete="off"
                >
                    <Form.Item
                        label="投稿标题"
                        name="draftTitle"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your username!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="投稿内容"
                        name="draftContext"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your password!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item>
                        <Button
                            block
                            shape='round'
                            type="primary"
                            htmlType="submit"
                        >
                            新增课程
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};
export default PostDraft;